﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Eqwww.Data;
using Eqwww.Domain.Models.SystemManage;
using Eqwww.App.SystemManage;
using Eqwww.App.Authorize;
using Eqwww.Code;

namespace Eqwww.Web.Areas.SystemSecurity.Controllers
{
    [Area("SystemSecurity")]
    public class DatabaseLogController : ControllerBase
    {
        private DatabaseLogApp _dbLogApp;
        private AuthorizeApp _authorizeApp;

        public DatabaseLogController(DatabaseLogApp databaseLogApp, AuthorizeApp authorizeApp)
        {
            _dbLogApp = databaseLogApp;
            _authorizeApp = authorizeApp;
        }

        [AuthFilter]
        // GET: SystemSecurity/DatabaseLog
        public IActionResult Index(string filter, int? pageIndex, int? pageSize)
        {
            var currentModuleCode = "SystemSecurity_DatabaseLog";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Initial);

            return View();
        }

        public IActionResult GridJson(Pagination pagination, string keyword, DbLogOperationType? DbLogOperationType, string btime, string etime)
        {
            DateTime? BTime = null;
            DateTime? ETime = null;
            if (!string.IsNullOrEmpty(btime))
                BTime = DateTime.Parse(btime);
            if (!string.IsNullOrEmpty(etime))
                ETime = DateTime.Parse(etime);
            var data = new
            {
                rows = _dbLogApp.GetPagedList(pagination, keyword, DbLogOperationType, BTime, ETime),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        [AuthFilter]
        public async Task<IActionResult> Details(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var databaseLogModel = await _dbLogApp.GetAsync(id);
            if (databaseLogModel == null)
            {
                return NotFound();
            }

            return View(databaseLogModel);
        }

        [AuthFilter]
        public IActionResult ClearLog()
        {
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult ClearLogSubmit(int ck)
        {
            return Json(_dbLogApp.ClearLog(ck));
        }

    }
}
